// #ifndef H5 || MP-WEIXIN
import axios from './axios.js'
// #endif
// #ifdef H5 || MP-WEIXIN
import axios from './axios_browser.js'
// #endif
import application from '@/config.js'


import {
	getToken,
	setToken,
	getRefreshToken,
	setRefreshToken,
	clearStorage
} from '../utils/auth'


function settle(resolve, reject, response) {
	var validateStatus = response.config.validateStatus;
	if (!response.status || !validateStatus || validateStatus(response.status)) {
		resolve(response);
	} else {
		reject(response);
	}
};

const instance = axios.create({
	baseURL: application.AppURL || "",
	timeout: application.timeout || 100000,
	withCredentials: true,
	crossDomain: true,
	adapter: function(config) {
		return new Promise((resolve, reject) => {
			uni.request({
				method: config.method.toUpperCase(),
				url: axios.getUri(config),
				header: JSON.parse(JSON.stringify(config.headers)),
				data: config.data,
				dataType: config.dataType,
				responseType: config.responseType,
				sslVerify: config.sslVerify,
				complete: function complete(response) {
					response = {
						data: response.data,
						status: response.statusCode,
						errMsg: response.errMsg,
						header: response.header,
						config: config
					};
					settle(resolve, reject, response);
				},
			});
		})
	}
})

// 请求拦截
instance.interceptors.request.use(
	config => {
		let token = getToken();
		//设置请求头
		if (token) {
			config.headers['Authorization'] = 'Bearer ' + token;
		}
		let refreshToken = getRefreshToken();
		//设置请求头
		if (refreshToken) {
			config.headers['RefreshToken'] = refreshToken;
		}
		//此处不处理异常
		try {
			config.headers['x-api-id'] = application.aid || '-1'
			config.headers['x-api-name'] = application.path || 'null'
		} catch (e) {}
		console.log("发送的请求信息", config)
		//返回配置信息
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

// 响应拦截
instance.interceptors.response.use(
	response => {
		console.log(`[DEBUG:请求成功「${new Date()}」]`, response)
		if (response.status >= 200 && response.status < 300) {
			if (response.data.code === 0) {
				//用于Token存储
				if (response.data.token) {
					setToken(response.data.token);
				}
				//用于RefreshToken存储
				if (response.data.refreshToken) {
					setRefreshToken(response.data.refreshToken);
				}
				return Promise.resolve(response.data.data)
			} else {
				//处理40000-50000自动报错
				if (response.data.code >= 40000 && response.data.code < 50000) {
					uni.showModal({
						title: '系统错误',
						content: response.data.msg || 'Error',
					});
				}
				return Promise.reject(response.data)
			}
		}
		return Promise.reject(response)
	},
	error => {
		console.error(`[DEBUG:请求报错「${new Date()}」]`, error)
		if (error.status > 300) {
			if (error.data.code) {
				uni.showToast({
					icon: "none",
					title: error.data.msg || '网络异常！',
				});
			}
		}
		if (error.status == 401) {
			clearStorage();
		}
		return Promise.reject(error);
	}
);



export default instance